package com.dlc.felear.xiaoensale.helper;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.dlc.felear.xiaoensale.constant.Constant;
import com.dlc.felear.xiaoensale.deviceUtil.Serialhelper;
import com.dlc.felear.xiaoensale.dlc_serial_port.DlcSerialPortClient;
import com.dlc.felear.xiaoensale.entity.BleRssiDevice;

import org.simple.eventbus.EventBus;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.concurrent.ArrayBlockingQueue;

import cn.com.heaton.blelibrary.ble.Ble;
import cn.com.heaton.blelibrary.ble.callback.BleScanCallback;

public class BlueToochHelper implements Handler.Callback {
    private final String TAG = "BlueToochHelper";
    private static BlueToochHelper instance;
    private static final int SEARCH_RETRY = 1212;
    private static final int SEARCH_TIME_OUT = 1211;
    private static final int SEARCH_CLAASIC = 1213;
    public static final String AT_SCAN_CANCEL = "AT+SCAN=0";
    public static final String AT_SCAN_CMD = "AT+SCAN\n";
    public static final String AT_SOP_CMD = "AT+SCAN=0,1,1\n";
    public static final String AT_RESTART_CMD = "AT +RESTART\n";
    private Context context;
    private String deviceModel;
    public String deviceType = "";
    private static final String search_ble_fail = "notFoundBlueDevice";
    private Handler handler;
    private BluetoothManager bluetoothManager;
    private HashMap<String, String> blueDevices = new HashMap<>();
    private Session session;
    private boolean isQuery = false;
    private Ble ble;
    private static ArrayBlockingQueue<String> mQueue = new ArrayBlockingQueue<>(100);
    private long tempTimestap = 0;
    private int rssi = -1;
    private int timeOut = 12000;

    /**
     * funtionModel 1 外置蓝牙模块  2 系统BLE蓝牙 3 系统经典蓝牙 4 系统经典、BLE 5 使用所有方式
     */
    private int funtionModel = 0;
    private int isSuccess=0;



    private BlueToochHelper(Context context) {
        log(TAG);
        this.context = context;
        session = Session.getSession();
        initData(context);
        loop();
    }

    /**
     * 初始化数据
     *
     * @param context
     */
    private void initData(Context context) {
        try {
            deviceType = session.getString(Constant.GZDKSJ, "AOSMITH_1745");
            deviceModel = session.getString(Constant.DCFYCGB);
            bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
            bluetoothManager.getAdapter().enable();
            handler = new Handler(this);
            ble = Ble.getInstance();
            setParamer(deviceType, deviceModel);
            setTimeOut(session.getInt(Constant.SEARCH_TIME_OUT, 12000),
                    session.getInt(Constant.BLUE_RSSI, -50));
            setLyParamer(session.getInt(Constant.FUNTION_TYPE, 1));
        } catch (Exception e) {
            showToast("BinitData:" + e.getMessage());
        }
    }

    private BleScanCallback<BleRssiDevice> scanCallback = new BleScanCallback<BleRssiDevice>() {
        @Override
        public void onLeScan(final BleRssiDevice result, int rssi, byte[] scanRecord) {
            try {
                log("onLeScan:" + JsonHelper.toJson(result));
                addQeueue("ble", result.getBleName(), result.getBleAddress(), "-1");
            } catch (Exception e) {
                showToast("BleScanCallback->onLeScan:" + e.getMessage());
            }
        }
    };


    /**
     * 发送AT 命令到USB蓝牙模块
     *
     * @param cmd
     */
    public void sendMsgToUsbBy(String cmd) {
        EventBus.getDefault().post(cmd.getBytes(StandardCharsets.UTF_8), Constant.EVENT_RECEIVE_INPU_IO11);
    }

    /**
     * 搜索蓝牙
     */
    public void searchBlueDevice(String deviceType) {
        try {
            log("蓝牙型号:" + deviceType);
//            if (isQuery) {
//                xianshiMsg("忽略这次蓝牙搜索");
//                return;
//            }
            if (!bluetoothManager.getAdapter().isEnabled()) {
                bluetoothManager.getAdapter().enable();
            }
            this.deviceType=deviceType;
            tempTimestap = System.currentTimeMillis();
            isQuery = true;
            log("搜索蓝牙");
            blueDevices.clear();
            xianshiMsg("接收蓝牙搜索指令,蓝牙名称型号:" + deviceType);
            EventBus.getDefault().post(new HashMap<String, BluetoothDevice>(), Constant.RECIEVE_LY);
            handler.removeMessages(SEARCH_RETRY);
            handler.removeMessages(SEARCH_TIME_OUT);
            handler.removeMessages(SEARCH_CLAASIC);
            if (funtionModel == 1) {
                isSuccess+=1;
                log("BlueToochHelper: blueName:Watch_8 搜索蓝牙");
                sendMsgToUsbBy(AT_SOP_CMD);
                sendMsgToUsbBy(AT_SCAN_CMD);
                sendMsgToUsbBy(AT_SCAN_CMD);
                handler.sendEmptyMessageDelayed(SEARCH_RETRY, 5000);
            } else if (funtionModel == 2) {
                scanBluetoothDevices(deviceType);
                handler.sendEmptyMessageDelayed(SEARCH_RETRY, 4000);
                handler.sendEmptyMessageDelayed(SEARCH_RETRY, 8000);
            } else if (funtionModel == 3) {
                startDiscovery();
                handler.sendEmptyMessageDelayed(SEARCH_CLAASIC, 6000);
            } else if (funtionModel == 4) {
                scanBluetoothDevices(deviceType);
                startDiscovery();
                handler.sendEmptyMessageDelayed(SEARCH_CLAASIC, 6000);
                handler.sendEmptyMessageDelayed(SEARCH_RETRY, 4000);
                handler.sendEmptyMessageDelayed(SEARCH_RETRY, 8000);
            } else {
                sendMsgToUsbBy(AT_SCAN_CMD);
                scanBluetoothDevices(deviceType);
                startDiscovery();
                handler.sendEmptyMessageDelayed(SEARCH_CLAASIC, 6000);
                handler.sendEmptyMessageDelayed(SEARCH_RETRY, 4000);
                handler.sendEmptyMessageDelayed(SEARCH_RETRY, 8000);
            }
            handler.sendEmptyMessageDelayed(SEARCH_TIME_OUT, timeOut);
            EventBus.getDefault().post(true, Constant.SOUSUO_STATUS);
        } catch (Exception e) {
            showToast("数据异常:" + e.getMessage());
        }
    }

    private void stopScaner() {
        handler.removeMessages(SEARCH_RETRY);
        handler.removeMessages(SEARCH_TIME_OUT);
        handler.removeMessages(SEARCH_CLAASIC);
        if (funtionModel == 1) {
            sendMsgToUsbBy(AT_SOP_CMD);
        } else if (funtionModel == 2) {
            ble.stopScan();
        }
    }

    public void scanBluetoothDevices(String nama) {
        deviceType = nama;
        bleStartBleScan();
    }

    private void addQeueue(String tag, String name, String addr, String ssir) {
        try {
            log("addQeueue name:" + name + " addr:" + addr +"rssi:"+ssir+ "  tag:" + tag);
            if (!TextUtils.isEmpty(name)) {
                mQueue.put(name + "," + addr + "," + ssir);
            }
        } catch (Exception e) {

        }
    }

    public void loop() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String s = null;
                    while ((s = mQueue.take()) != null) {
                        String[] tempArr = s.split(",");
                        if (tempArr != null && tempArr.length == 3) {
                            handleSearchResult(tempArr[0], tempArr[1], tempArr[2]);
                        }
                    }
                } catch (Exception e) {
                    loop();
                }
            }
        }).start();
    }

    private void handleSearchResult(String blueName, String blueAddr, String ssir) {
       try {
           if (!TextUtils.isEmpty(blueName)) {
               xianshiMsg("搜索结果:" + blueName + " rssi="+ ssir);
           }
//        log("blueName:"+blueName+"扫秒时长：" + (System.currentTimeMillis() - tempTimestap) / 1000 + "秒");
           log("blueName:"+blueName+" blueAddr:"+blueAddr+" ssir:"+ssir+" deviceType:"+deviceType+" stdRssi:"+this.rssi);
           int intRssi = Integer.parseInt(ssir);
           if (!TextUtils.isEmpty(blueName) && blueName.contains(deviceType) && intRssi > this.rssi) {
               blueDevices.put(blueName + "_" + blueAddr, blueName);
               EventBus.getDefault().post(blueDevices, Constant.RECIEVE_LY);
               sendBlueMsg(blueName);
               isSuccess-=1;
           }
           log("blueName:"+blueName+" isSuccess:"+isSuccess);
       }catch (Exception e){
           xianshiMsg("handleSearchResult:"+e.getMessage());
       }
    }




    private void bleStartBleScan() {
        try {
            if (ble.isScanning()) {
                ble.stopScan();
                handler.sendEmptyMessageDelayed(110110, 500);
            } else {
                xianshiMsg("启动BLE蓝牙搜索");
                ble.startScan(scanCallback);
            }
        } catch (Exception e) {
            showToast("bleStartBleScan:" + e.getMessage());
        }
    }


    private void startDiscovery() {
        try {
            EventBus.getDefault().post(true, Constant.SOUSUO_STATUS);
            if (!bluetoothManager.getAdapter().isEnabled()) {
                bluetoothManager.getAdapter().enable();
                xianshiMsg("打开蓝牙");
            }
            if (bluetoothManager.getAdapter().isDiscovering()) {
                log("startDiscovery: 已经在搜索蓝牙");
//                xianshiMsg("取消上一次蓝牙搜索，并重新搜索");
                bluetoothManager.getAdapter().cancelDiscovery();
            }
            boolean bb = bluetoothManager.getAdapter().startDiscovery();
            xianshiMsg("启动经典蓝牙搜索，启动状态：" + bb);
            log("startDiscovery:" + bb);
        } catch (Exception e) {
            showToast("startDiscovery:" + e.getMessage());
        }
    }

    public static BlueToochHelper getInstance(Context context) {
        if (instance == null) {
            synchronized (BlueToochHelper.class) {
                if (instance == null) {
                    instance = new BlueToochHelper(context);
                }
            }
        }
        return instance;
    }


    private void showToast(String msg) {
        log("showToast:" + msg);
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
    }

    private void log(String msg) {
        saveLog(msg);
        Log.e(TAG, msg);
    }

    /**
     * 接受蓝牙信息
     *
     * @param device
     */
    public void onDeviceFounded(BluetoothDevice device) {
        try {
            addQeueue("class", device.getName(), device.getAddress(), "-1");
        } catch (Exception e) {
            showToast("数据异常 onDeviceFounded:" + e.getMessage());
        }
    }

    public void onDeviceFounded(String name, String addr, String ssir) {
        try {
            addQeueue("class", name, addr, ssir);
        } catch (Exception e) {
            showToast("数据异常 onDeviceFounded:" + e.getMessage());
        }
    }


    private void sendBlueMsg(String bleName) {
        try {
            isQuery = false;
            log("sendBlueMsg:" + JsonHelper.toJson(blueDevices));
            handler.removeMessages(SEARCH_RETRY);
            handler.removeMessages(SEARCH_TIME_OUT);
            DlcSerialPortClient.getInstance().send(Serialhelper.getInstance()
                    .getKzbSerialNo(), bleName.getBytes(StandardCharsets.US_ASCII));
            EventBus.getDefault().post(false, Constant.SOUSUO_STATUS);
            EventBus.getDefault().post(blueDevices, Constant.RECIEVE_LY);
            xianshiMsg("返回蓝牙名称:" + bleName);
            stopScaner();
        } catch (Exception e) {
            showToast("sendBlueMsg:" + e.getMessage());
        }
    }


    public void clearData() {
        try {
            log("clearData");
            isQuery = false;
            handler.removeMessages(SEARCH_RETRY);
            handler.removeMessages(SEARCH_CLAASIC);
            handler.removeMessages(SEARCH_TIME_OUT);
            ble.stopScan();
            bluetoothManager.getAdapter().cancelDiscovery();
            EventBus.getDefault().post(false, Constant.SOUSUO_STATUS);
            xianshiMsg("clearData");
        } catch (Exception e) {
            showToast("clearData:" + e.getMessage());
        }
    }


    @Override
    public boolean handleMessage(Message msg) {
        try {
            if (SEARCH_TIME_OUT == msg.what) {
                //蓝牙搜索超时
                log("蓝牙搜索超时");
                timeOut();
            } else if (SEARCH_RETRY == msg.what) {
                log("发送蓝牙搜索结果");
                tryAgin();
            } else if (110110 == msg.what) {
                xianshiMsg("再次启动BLE蓝牙搜索");
                ble.startScan(scanCallback);
            } else if (SEARCH_CLAASIC == msg.what) {
                xianshiMsg("再次启动经典蓝牙搜索");
                startDiscovery();
            }
        } catch (Exception e) {
            showToast("数据异常:" + e.getMessage());
        }
        return false;
    }

    private void timeOut() {
        log("开始发送蓝牙数据");
        isQuery = false;
        ble.stopScan();
        if (blueDevices.isEmpty()) {
            DlcSerialPortClient.getInstance().send(Serialhelper.getInstance().getKzbSerialNo(),
                    search_ble_fail.getBytes(StandardCharsets.US_ASCII));
            xianshiMsg("未收到符合条件的蓝牙名称");
        } else {
            for (String key : blueDevices.keySet()) {
                sendBlueMsg(blueDevices.get(key));
            }
        }
        EventBus.getDefault().post(false, Constant.SOUSUO_STATUS);
    }

    private void tryAgin() {
//        log("tryAgin:" + JsonHelper.toJson(blueDevices));
        xianshiMsg("因超时重新启动BLE蓝牙搜索,默认型号：" + deviceType + " funtionModel:" + funtionModel);
        if (funtionModel == 1) {
            sendMsgToUsbBy(AT_SOP_CMD);
            sendMsgToUsbBy(AT_SCAN_CMD);
        } else if (funtionModel == 2) {
            scanBluetoothDevices(deviceType);
        } else if (funtionModel == 3) {
            startDiscovery();
        } else if (funtionModel == 4) {
            scanBluetoothDevices(deviceType);
            startDiscovery();
        } else {
            sendMsgToUsbBy(AT_SCAN_CMD);
            scanBluetoothDevices(deviceType);
            startDiscovery();
        }
    }

    public void setParamer(String name, String type) {
        deviceType = name;
        deviceModel = type;
//        deviceType="Watch_8";
        log("name:" + name + " type:" + type);
    }

    public void stopScan() {
        try {
            handler.removeMessages(SEARCH_RETRY);
            handler.removeMessages(SEARCH_TIME_OUT);
            handler.removeMessages(SEARCH_CLAASIC);
            ble.stopScan();
            bluetoothManager.getAdapter().cancelDiscovery();
        } catch (Exception e) {

        }
    }

    public void sendHandsha() {
        try {
            DlcSerialPortClient.getInstance().send(Serialhelper.getInstance().getKzbSerialNo(),
                    deviceModel.getBytes(StandardCharsets.US_ASCII));
        } catch (Exception e) {
            showToast("数据异常:" + e.getMessage());
        }
    }

    public void clearBluData() {
        isQuery = false;
        blueDevices.clear();
        EventBus.getDefault().post(blueDevices, Constant.RECIEVE_LY);
    }

    private void xianshiMsg(String msg) {
        saveLog(msg);
        EventBus.getDefault().post(msg, Constant.SERIALMSG);
    }

    private void saveLog(String msg) {
//        LogToFile.getInstance().input2File(msg+"   "+ TimeUtils.getCurrrentTimeYMDHMS());
    }

    public void setTimeOut(int timeOut, int rssi) {
        this.timeOut = timeOut;
        this.rssi = rssi;
        if(this.timeOut<=12000){
            this.timeOut=12000;
        }
    }

    public void setLyParamer(int funtionModel) {
        this.funtionModel = funtionModel;
    }
}
